<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>公告管理</span>
        <el-button type="primary" @click="openDrawer">发布公告</el-button>
      </div>
    </template>

    <!-- 公告列表 -->
    <el-table :data="announcements" style="width: 100%">
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="createUserName" label="发布人" width="120" />
      <el-table-column prop="createTime" label="发布时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="editAnnouncement(row)">编辑</el-button>
          <el-button type="danger" link @click="deleteAnnouncement(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 公告编辑抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="announcementModel.id ? '编辑公告' : '发布公告'" direction="rtl" size="50%">
      <el-form ref="formRef" :model="announcementModel" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementModel.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="announcementModel.content" type="textarea" :rows="10" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">发布</el-button>
          <el-button @click="saveAsDraft">保存草稿</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { announcementListService, announcementAddService, announcementUpdateService, announcementDeleteService } from '@/api/announcement.js'
import useUserInfoStore from '@/stores/userInfo.js'

const userInfoStore = useUserInfoStore()

// 公告列表数据
const announcements = ref([])

// 抽屉显示状态
const visibleDrawer = ref(false)

// 表单引用
const formRef = ref(null)

// 公告表单数据
const announcementModel = ref({
  title: '',
  content: '',
  status: 1,
  createUser: userInfoStore.info.id,
  createUserName: userInfoStore.info.username
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
  ]
}

// 获取公告列表
const getAnnouncementList = async () => {
  try {
    const res = await announcementListService()
    if (res.code === 0) {
      announcements.value = res.data
    } else {
      ElMessage.error(res.msg || '获取公告列表失败')
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败')
  }
}

// 打开抽屉
const openDrawer = () => {
  announcementModel.value = {
    title: '',
    content: '',
    status: 1,
    createUser: userInfoStore.info.id,
    createUserName: userInfoStore.info.username
  }
  visibleDrawer.value = true
}

// 编辑公告
const editAnnouncement = (row) => {
  announcementModel.value = { ...row }
  visibleDrawer.value = true
}

// 删除公告
const deleteAnnouncement = (row) => {
  ElMessageBox.confirm('确认删除该公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await announcementDeleteService(row.id)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        getAnnouncementList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await (announcementModel.value.id ? 
          announcementUpdateService(announcementModel.value) : 
          announcementAddService(announcementModel.value))
        
        if (res.code === 0) {
          ElMessage.success('发布成功')
          visibleDrawer.value = false
          getAnnouncementList()
        } else {
          ElMessage.error(res.msg || '发布失败')
        }
      } catch (error) {
        console.error('发布失败:', error)
        ElMessage.error('发布失败')
      }
    }
  })
}

// 保存草稿
const saveAsDraft = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        announcementModel.value.status = 0
        const res = await (announcementModel.value.id ? 
          announcementUpdateService(announcementModel.value) : 
          announcementAddService(announcementModel.value))
        
        if (res.code === 0) {
          ElMessage.success('保存成功')
          visibleDrawer.value = false
          getAnnouncementList()
        } else {
          ElMessage.error(res.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 组件挂载时获取公告列表
onMounted(() => {
  getAnnouncementList()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style> 